// pages/api/upload.ts
// import formidable, { IncomingForm } from 'formidable';
// import fs from 'fs';
// import path from 'path';




// export const config = {
//   api: {
//     bodyParser: false, // 禁用 Next.js 默认的 body parser，因为我们要自己处理
//   },
// };

// const uploadDir = path.join(process.cwd(), 'public', 'uploads'); // 上传文件保存的路径

// export default function handler(req: any, res: any) {
//   const form = new IncomingForm();
//   form.uploadDir = uploadDir; // 指定上传目录
//   form.keepExtensions = true; // 保持文件扩展名

//   // 创建上传目录（如果不存在）
//   if (!fs.existsSync(uploadDir)) {
//     fs.mkdirSync(uploadDir, { recursive: true });
//   }

//   form.parse(req, (err: any, fields: any, files: { file: any[]; }) => {
//     if (err) {
//       console.error('File upload error:', err);
//       return res.status(500).json({ error: 'Something went wrong' });
//     }

//     const uploadedFile = files.file[0];
//     console.log('Uploaded file:', uploadedFile);

//     res.status(200).json({
//       message: 'File uploaded successfully',
//       file: uploadedFile,
//     });
//   });
// }

import { NextResponse } from 'next/server';
import mammoth from 'mammoth';
import { PostService } from '@/utils/prisma';


// 处理 POST 请求上传文件
export async function POST(req: Request) {

    const formData = await req.formData();
    const files = formData.get('file') as File;
    const id = formData.get('id') as string;
    console.log(id)
    // 获取上传文件的详细信息

    // console.log(files, 888)

    const fileType = files.type; // 获取文件 MIME 类型
    let content = '';
    const title = files.name.slice(0, files.name.lastIndexOf('.'));
    // console.log(title); // 输出: document
    try {
        if (fileType === 'text/plain') {
            let contentLsit = [{
                id: 0, en_text: title, zh_text: '没有翻译'
            }];
            // 读取 TXT 文件内容
            content = await files.text();
            const sentences = (content.match(/[^.!?]+[.!?]+/g) || [])
            sentences.forEach((sentence, index) => {
                const item = {
                    id: index + 1,
                    en_text: sentence.replace(/^[”\r\n\s]+/, ''),
                    zh_text: '没有翻译',
                }
                contentLsit.push(item);
            });
            // console.log(contentLsit)
           const a =  await PostService.createPost(
                title, contentLsit, id, "my"
            )
            console.log(a)
        } else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
            let contentLsit = [{
                id: 0, en_text: title, zh_text: '没有翻译'
            }];
            // 读取 DOCX 文件内容
            const arrayBuffer = await files.arrayBuffer();
            const result = await mammoth.extractRawText({ buffer: Buffer.from(arrayBuffer) });
            let content = result.value;

            // 清理多余的空行和空格
            content = content.replace(/\r\n|\n|\r/g, " ").replace(/\s+/g, " ").trim();

            // 定义一个正则表达式，用于按句号、问号或感叹号来分割句子，但保留对话标点（如 "Mr."）
            const sentenceRegex = /(?<=\.|\!|\?)\s+/g;

            // 处理文本，保留对话引号、特定缩写（如 Mr.）
            let sentences = content.split(sentenceRegex);

            // 清理每个句子，并确保没有多余的空格
            sentences = sentences.map(sentence => sentence.trim());

            // 输出每个句子
            sentences.forEach((sentence, index) => {
                // console.log(`第 ${index + 1} 句: ${sentence}`);
                const item = {
                    id: index + 1,
                    en_text: sentence.replace(/^[”\r\n\s]+/, ''),
                    zh_text: '没有翻译',
                }
                contentLsit.push(item);
            });
            console.log(contentLsit)
            await PostService.createPost(
                title, contentLsit, id, "my"
            )
        } else {
            return NextResponse.json({ error: 'Unsupported file type', status: 200 }, { status: 400 });
        }
        return NextResponse.json({
            message: "success",
            data: [],
            status: 200
        })
    } catch (e) {
        console.log("uplaod fail", e)
        return NextResponse.json({
            data: "upload failed",
            status: 200
        })
    }
}
